//
//  2_两数相加.swift
//  playground_cmd_leetcode
//
//  Created by objcat on 2022/1/12.
//

import Foundation
/**
 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。

 请你将两个数相加，并以相同形式返回一个表示和的链表。

 你可以假设除了数字 0 之外，这两个数都不会以 0 开头。

  

 示例 1：


 输入：l1 = [2,4,3], l2 = [5,6,4]
 输出：[7,0,8]
 解释：342 + 465 = 807.
 示例 2：

 输入：l1 = [0], l2 = [0]
 输出：[0]
 示例 3：

 输入：l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 输出：[8,9,9,9,0,0,0,1]
  

 提示：

 每个链表中的节点数在范围 [1, 100] 内 `0 <= Node.val <= 9`
 题目数据保证列表表示的数字不含前导零

 来源：力扣（LeetCode）
 链接：https://leetcode-cn.com/problems/add-two-numbers
 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */

public class ListNode {
    public var val: Int
    public var next: ListNode?
    public init() { self.val = 0; self.next = nil; }
    public init(_ val: Int) { self.val = val; self.next = nil; }
    public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
}

extension Solution {
    
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        let number1 = nodeToReversedInt(node: l1)
        let number2 = nodeToReversedInt(node: l2)
        let sum = number1 + number2
        return intToNode(int: sum)
    }
    
    func nodeToReversedInt(node: ListNode?) -> Int {
        var nextNode: ListNode? = node
        var arr: Array<String> = []
        repeat {
            let tmp = String(nextNode!.val)
            arr.append(tmp)
            nextNode = nextNode?.next
        } while nextNode != nil
        return Int(arr.reversed().joined()) ?? 0
    }

    func intToNode(int: Int) -> ListNode? {
        let arr = String(int).compactMap({ return Int(String($0)) })
        let reversedArr = Array(arr.reversed())
        let firstNode = ListNode(reversedArr.first ?? 0)
        var currentNode = firstNode
        for number in reversedArr[1...] {
            let next = ListNode(number)
            currentNode.next = next
            currentNode = next
        }
        return firstNode
    }

    func listToNode(list: Array<Int>) -> ListNode? {
        let reversedList = Array(list.reversed())
        let firstNode = ListNode(reversedList.first ?? 0)
        var currentNode = firstNode
        for i in reversedList[1...] {
            let nextNode = ListNode()
            nextNode.val = i
            currentNode.next = nextNode
            currentNode = nextNode
        }
        return firstNode
    }
    
    func testAddTwoNumbers(run: Bool) {
        guard run else { return }
        let l1 = listToNode(list: [2, 4, 3])
        let l2 = listToNode(list: [5, 6, 4])
        
//        let l1 = listToNode(list: [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1])
//        let l2 = listToNode(list: [5, 6, 4])

        let node = addTwoNumbers(l1, l2)
        print(node ?? "")
        
        
    }
    
}


